package com.study.demo.springmvc.controller;

import com.alibaba.fastjson.JSON;
import com.study.demo.springmvc.model.User;
import com.study.demo.springmvc.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * @author: elvin
 * @time: 2019-05-05 13:29
 * @desc:
 **/
@RestController
@RequestMapping("api")
public class ApiController {

    @Autowired
    private UserValidator validator;

    @InitBinder
    private void initBinder(WebDataBinder binder){
        binder.addValidators(validator);
    }

    @ModelAttribute("name")
    public String setModel(){
        return "xiaoming";
    }

    @ModelAttribute
    public void setModel1(Model model){
        model.addAttribute("age", 20);
    }

    @ModelAttribute
    public String setModel2(){
        return "model2";
    }

    @GetMapping("getUser")
    public User getUser(Model model){
        User u = new User();
        Map<String, Object> m = model.asMap();
        u.setName(m.get("name") + "");
        u.setAge(Integer.valueOf(m.get("age") + ""));
        System.out.println(m.get("string"));
        return u;
    }

    @GetMapping("getStrUser")
    public String getStrUser(Model model){
        User user = getUser(model);
        return JSON.toJSONString(user);
    }

    @GetMapping("setUser")
    public String setUser(@Valid User user, BindingResult erros ){
        String msg = "";
        if(erros.hasErrors()){
            for (ObjectError error : erros.getAllErrors()) {
                msg += error.getDefaultMessage();
                System.out.println(error.getDefaultMessage());
            }
        }
        return msg;
    }
}
